package com.imooc.springboot.dubbo.nilinili.provider.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.imooc.springboot.dubbo.nilinili.entity.bean.PageBean;
import com.imooc.springboot.dubbo.nilinili.entity.dto.CommentDTO;
import com.imooc.springboot.dubbo.nilinili.entity.dto.MyCommentDTO;
import com.imooc.springboot.dubbo.nilinili.provider.entity.po.CommentPO;
import com.imooc.springboot.dubbo.nilinili.provider.entity.po.MyCommentPO;
import com.imooc.springboot.dubbo.nilinili.provider.mapper.CommentMapper;
import com.imooc.springboot.dubbo.nilinili.provider.utils.BeanCopierUtil;
import com.imooc.springboot.dubbo.nilinili.provider.utils.JwtToUserId;
import com.imooc.springboot.dubbo.nilinili.res.CodeEnum;
import com.imooc.springboot.dubbo.nilinili.res.ResultFactory;
import com.imooc.springboot.dubbo.nilinili.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = CommentService.class)
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Override
    public List<CommentDTO> selectCommentByPhotoId(Integer id) {
        List<CommentPO> commentPOS = commentMapper.selectCommentByPhotoId(id);
        return BeanCopierUtil.copyObjects(commentPOS,CommentDTO.class);
    }

    @Override
    @Transactional
    public boolean addComment(Integer photoId, String token, String content) {
        String user_id = JwtToUserId.Jwt2UserId(token);
        CommentPO commentPO = new CommentPO().builder().userId(user_id).content(content).photoId(photoId).build();
        Integer integer = commentMapper.addComment(commentPO);
        if (integer != 0){
            int count = commentMapper.getCommentCount(photoId.toString());
            commentMapper.addCommentCount(photoId.toString(),count);
            return true;
        }
        return false;
    }

    @Override
    public String getCommentByUserId(String token,int pageNum) {
        String user_id = JwtToUserId.Jwt2UserId(token);
        PageHelper.startPage(pageNum, 10);
        List<MyCommentPO> commentByUserId = commentMapper.getCommentByUserId(user_id);
        PageBean<MyCommentPO> pageInfo = new PageBean<>(commentByUserId);
        PageBean<MyCommentDTO> pageBean = BeanCopierUtil.CopyPageBean(pageInfo, MyCommentDTO.class);
        return ResultFactory.createResult(CodeEnum.SUCCESS, "查询成功", pageBean);
    }

    //删除评论
    @Override
    @Transactional
    public boolean deleteComment(String id) {
        Integer integer = commentMapper.deleteComment(id);
        if (integer != 0){
            return true;
        }
        return false;
    }



}
